//
//  AppDelegate.m
//  BanBanApp
//
//  Created by 时伟平 on 16/5/26.
//  Copyright © 2016年 时伟平. All rights reserved.
//

#import "AppDelegate.h"
#import "BXTabBarController.h"
#import "LeftViewController.h"
#import "RootViewController.h"

#import "UserManager.h"

#import "RealReachability.h"//网络检查

#import "LoginMainViewController.h"




@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
   
    
    
    // iOS8 注册APNS
    if ([application respondsToSelector:@selector(registerForRemoteNotifications)]) {
        UIMutableUserNotificationAction *action = [[UIMutableUserNotificationAction alloc] init];
        action.title = @"查看消息";
        action.identifier = @"action1";
        action.activationMode = UIUserNotificationActivationModeForeground;
        
        UIMutableUserNotificationCategory *category = [[UIMutableUserNotificationCategory alloc] init];
        category.identifier = @"alert";
        [category setActions:@[action] forContext:UIUserNotificationActionContextDefault];
        
        
        UIUserNotificationType notificationTypes = UIUserNotificationTypeBadge |UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:notificationTypes categories:[NSSet setWithObjects:category, nil]];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        
    }

    
    [self checkNetWork];
 

    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];

    UserManager *manager = [UserManager shareInstance];
    BOOL skip = [manager skipLoginPage];
   //保存了账号 密码  不需要进登录页
    if (skip) {
            BXTabBarController *mainVC = [[BXTabBarController alloc]init];
            LeftViewController *left = [[LeftViewController alloc]init];
            RootViewController *root = [[RootViewController alloc]initWithContentViewController:mainVC leftMenuViewController:left rightMenuViewController:nil];
           root.appdelegate = @"AppDelegate";
            self.window.rootViewController = root;
        
    }else{
        LoginMainViewController *loginMainVC = [[LoginMainViewController alloc]init];
        UINavigationController *loginNav = [[UINavigationController alloc]initWithRootViewController:loginMainVC];
        self.window.rootViewController = loginNav;
    }
    

   [self.window makeKeyAndVisible];
    
    
    
    
    /**
     *  APP未启动时 通过推送消息进入
     */
    
    if (launchOptions)
    {
        NSDictionary *pushDic = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        
        if (pushDic)
        {
            
                NSLog(@"remoteNotification%@",pushDic);
       
            
        }
    }
    
    
    
    
    
    
    return YES;
}




/**
 *  网络检查
 *
 *  @param networkChanged: 链接网络改变
 *
 */
-(void)checkNetWork{

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(networkChanged:)
                                                 name:kRealReachabilityChangedNotification
                                               object:nil];
    
    ReachabilityStatus status = [GLobalRealReachability currentReachabilityStatus];
    NSLog(@"Initial reachability status:%@",@(status));
    
    if (status == RealStatusNotReachable)
    {
        // @"Network unreachable!";
    }
    
    if (status == RealStatusViaWiFi)
    {
        // @"Network wifi! Free!";
    }
    
    if (status == RealStatusViaWWAN)
    {
        // @"Network WWAN! In charge!";
    }
    
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)networkChanged:(NSNotification *)notification
{
    RealReachability *reachability = (RealReachability *)notification.object;
    ReachabilityStatus status = [reachability currentReachabilityStatus];
    ReachabilityStatus previousStatus = [reachability previousReachabilityStatus];
    NSLog(@"networkChanged, currentStatus:%@, previousStatus:%@", @(status), @(previousStatus));
    
    if (status == RealStatusNotReachable)
    {
        // @"Network unreachable!";
    }
    
    if (status == RealStatusViaWiFi)
    {
        //@"Network wifi! Free!";
    }
    
    if (status == RealStatusViaWWAN)
    {
        //=@"Network WWAN! In charge!";
    }
    
    WWANAccessType accessType = [GLobalRealReachability currentWWANtype];
    
    if (status == RealStatusViaWWAN)
    {
        if (accessType == WWANType2G)
        {
           // @"RealReachabilityStatus2G";
        }
        else if (accessType == WWANType3G)
        {
            //@"RealReachabilityStatus3G";
        }
        else if (accessType == WWANType4G)
        {
            // @"RealReachabilityStatus4G";
        }
        else
        {
           // @"Unknown RealReachability WWAN Status, might be iOS6";
        }
    }
    
    
}




- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    
    NSLog(@"推送的内容：%@",notificationSettings);
    [application registerForRemoteNotifications];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{
    
    
    NSString *info = userInfo[@"aps"][@"alert"];
    
    NSLog(@"userinfo = %@",info);
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
#warning 将获取到的token传给SDK，用于苹果推送消息使用
 
    BXLog(@"deviceToken%@",deviceToken);
}

#warning 注册deviceToken失败；此处失败，与SDK无关，一般是您的环境配置或者证书配置有误
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"apns.failToRegisterApns", Fail to register apns)
                                                    message:error.description
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"ok", @"OK")
                                          otherButtonTitles:nil];
    [alert show];
}


//当应用程序正在运行的时候  接收到推送消息会执行这个方法
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    BXLog(@"应用程序正在运行的时候  接收到推送消息==%@",userInfo);
    
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
